package com.jeesite.modules.fl.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.jeesite.modules.fl.service.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.fl.entity.Appointment;
import com.jeesite.modules.fl.entity.Clinic;
import com.jeesite.modules.fl.entity.ClinicSetting;
import com.jeesite.modules.fl.entity.Leaguer;
import com.jeesite.modules.fl.entity.SysHoliday;
import com.jeesite.modules.fl.utils.DictProperties;
import com.jeesite.modules.fl.utils.Utils;
import com.jeesite.modules.sys.entity.Area;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.utils.UserUtils;

@Controller
@RequestMapping(value = "${adminPath}/fl/center")
public class CenterController extends BaseController{

	@Autowired
	private AppointmentService appointmentService;
	@Autowired
	private LeaguerService leaguerService;
	@Autowired
	private ClinicService clinicService;
	@Autowired
	private ClinicSettingService clinicSettingService;
	@Autowired
	private SysHolidayService holidayService;
	@Autowired
	private DoctorService doctorService;
	
	@RequestMapping(value = "center")
	public String center(Model model) {
        User user = UserUtils.getUser();
        Leaguer leaguer = leaguerService.get(user.getRefCode());
        model.addAttribute("user", user);
        model.addAttribute("leaguer", leaguer);
		return "modules/fl/center";
	}
	
	@RequestMapping(value = "getLeaguer")
	@ResponseBody
	public Leaguer getLeaguer() {
        User user = UserUtils.getUser();
        Leaguer leaguer = leaguerService.get(user.getRefCode());
        if(leaguer.getRealName() != null && !leaguer.getRealName().isEmpty()){
        	leaguer.setName(leaguer.getRealName());
        }
		return leaguer;
	}


	/**
	 * @param lang
	 * @param allowSchedule 允许预约
	 * @return
	 */
	@RequestMapping(value = "cityList")
	@ResponseBody
	public List<Area> cityList(String lang, String allowSchedule) {
		User user = UserUtils.getUser();
        Leaguer leaguer = leaguerService.get(user.getRefCode());
        String enterpriseId = leaguer.getEnterprise() == null?"":leaguer.getEnterprise().getId();
		List<Area> areas = clinicService.getArea(enterpriseId,allowSchedule);
		if(lang != null && "2".equals(lang)){
			for(Area area : areas){
				String label = DictProperties.getInstatnce().getAreaLabel(area);
				if(label != null){
					area.setAreaName(label);
				}
			}
		}
		return areas;
	}

	/**
	 * @param areaCode
	 * @param lang
	 * @param allowSchedule 允许预约
	 * @return
	 */
	@RequestMapping(value = "clinicList")
	@ResponseBody
	public List<Clinic> clinicList(String areaCode, String lang, String allowSchedule) {
		User user = UserUtils.getUser();
        Leaguer leaguer = leaguerService.get(user.getRefCode());
        String enterpriseId = leaguer.getEnterprise() == null?"":leaguer.getEnterprise().getId();
        List<Clinic> clinicList = clinicService.getClinic(areaCode, enterpriseId, allowSchedule);
        if(lang != null && "2".equals(lang)){
			clinicService.setListEngLang(clinicList);
        }
		return clinicList;
	}
	
	@RequestMapping(value = "getMyAppointment")
	@ResponseBody
	public List<Appointment> getMyAppointment(String lang) {
        User user = UserUtils.getUser();
        Leaguer leaguer = leaguerService.get(user.getRefCode());
        Appointment entity = new Appointment();
        entity.setStatus("0");
        entity.setLeaguer(leaguer);
        List<Appointment> list = appointmentService.findList(entity);
		if(lang != null && "2".equals(lang)) {
			for (Appointment appointment : list) {
				clinicService.setEngLang(appointment.getClinic());
				doctorService.setEngLang(appointment.getDoctor());
			}
		}
		return list;
	}
	
	@RequestMapping(value = "getValidDate")
	@ResponseBody
	public List<String> getValidDate(String clinicId, String department) {
		List<String> dates = new ArrayList<String>();
		Clinic clinic = clinicService.get(clinicId);
		ClinicSetting entity = new ClinicSetting();
    	entity.setClinic(clinic);
    	entity.setDepartment(department);
    	entity.setStatus("0");
    	String businessHours = null;
    	List<ClinicSetting> settingList = clinicSettingService.findList(entity);
    	if(settingList.size()>0){
    		ClinicSetting setting = settingList.get(0);
    		businessHours = setting.getBusinessHours();
    	}
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MONTH, 1);
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		Date endDate = calendar.getTime();
		Calendar calendar2 = Calendar.getInstance();
		calendar2.set(Calendar.HOUR_OF_DAY, 0);
		calendar2.set(Calendar.MINUTE, 0);
		calendar2.set(Calendar.SECOND, 0);
		calendar2.set(Calendar.MILLISECOND, 0);
		Date date = calendar2.getTime();
		SysHoliday holiday = new SysHoliday();
		holiday.setClinics(clinicId);
		holiday.setStatus("0");	
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
		while(date.before(endDate)){			
			holiday.setDate(date);
			List<SysHoliday> holidays = holidayService.findList(holiday);
			String result = sdf2.format(date);
			if(holidays.size()>0){
				if("2".equals(holidays.get(0).getHolidayStatus())){
					String week = holidays.get(0).getWeek();
					if(businessHours != null){
						Map<String, String> map = Utils.getBussinenssHours(week, businessHours);
						if(map.get("amStart") != null && map.get("pmStart") != null && (!map.get("amStart").equals("-1")||!map.get("pmStart").equals("-1"))){
							dates.add(result);
						}						
					}
				}
			}else{
				if(Utils.isBussinenssDay(result, clinic.getBusinessHours())){
					String week = Utils.toWeek(calendar2.get(Calendar.DAY_OF_WEEK));
					if(businessHours != null){
						Map<String, String> map = Utils.getBussinenssHours(week, businessHours);
						if(map.get("amStart") != null && map.get("pmStart") != null && (!map.get("amStart").equals("-1")||!map.get("pmStart").equals("-1"))){
							dates.add(result);
						}
					}
				}
			}	
			calendar2.add(Calendar.DATE, 1);
			date = calendar2.getTime();
		}
		return dates;
	}
	
	@RequestMapping(value = "getTimePeriod")
	@ResponseBody
	public List<String> getTimePeriod(String clinicId, String department, String date, String ampm) {		
		List<String> timePeriods = new ArrayList<String>();
		Clinic clinic = clinicService.get(clinicId);
//		if(!Utils.isBussinenssDay(date, clinic.getBusinessHours())){
//			return timePeriods;
//		}
		ClinicSetting entity = new ClinicSetting();
    	entity.setClinic(clinic);
    	entity.setDepartment(department);
    	entity.setStatus("0");
    	List<ClinicSetting> settingList = clinicSettingService.findList(entity);
    	if(settingList.size()>0){
    		Calendar calendar = Calendar.getInstance();
    		calendar.setTime(DateUtils.parseDate(date));
    		String week = Utils.toWeek(calendar.get(Calendar.DAY_OF_WEEK));
    		SysHoliday holiday = new SysHoliday();
    		holiday.setClinics(clinicId);
    		holiday.setStatus("0");	
    		holiday.setDate(DateUtils.parseDate(date));
    		List<SysHoliday> holidays = holidayService.findList(holiday);
    		if(holidays.size()>0){
    			if("2".equals(holidays.get(0).getHolidayStatus())){
    				week = holidays.get(0).getWeek();
				}
    		}
    		List<String> list = new ArrayList<String>();
    		ClinicSetting setting = settingList.get(0);
    		Integer serviceTime = setting.getServiceTime();
    		Integer number = setting.getNumber();
    		String businessHours = setting.getBusinessHours();
    		Map<String, String> map = Utils.getBussinenssHours(week, businessHours);
    		if("1".equals(ampm)){
	    		String	startTime = map.get("amStart");//setting.getAmStartTime();
	    		String	endTime = map.get("amEnd");//ssetting.getAmEndTime();
	    		if(startTime != null && endTime != null && !startTime.equals("-1")){
	    			list = Utils.getPeriods(date, startTime, endTime, serviceTime);
	    		}
    		}else if("2".equals(ampm)){
        		String	startTime = map.get("pmStart");//setting.getPmStartTime();
        		String	endTime = map.get("pmEnd");//setting.getPmEndTime();
        		if(startTime != null && endTime != null && !startTime.equals("-1")){
        			list = Utils.getPeriods(date, startTime, endTime, serviceTime);
        		}
        	}else{
        		String	startTime = map.get("amStart");//setting.getAmStartTime();
        		String	endTime = map.get("amEnd");//setting.getAmEndTime();
        		if(startTime != null && endTime != null && !startTime.equals("-1")){
        			list = Utils.getPeriods(date, startTime, endTime, serviceTime);
        		}
	    		startTime = map.get("pmStart");//setting.getPmStartTime();
	    		endTime = map.get("pmEnd");//setting.getPmEndTime();
	    		if(startTime != null && endTime != null && !startTime.equals("-1")){
	    			list.addAll(Utils.getPeriods(date, startTime, endTime, serviceTime));
	    		}
        	}
    		for(String period:list){
    			if(appointmentService.getAppointmentCountTime(clinicId, department, date, null, period) <number){
    				timePeriods.add(period);
    			}
    		}
    	}
		return timePeriods;
	}
	
	@RequestMapping(value = "viewAppointment")
	@ResponseBody
	public Appointment viewAppointment(String id,String lang) {
        Appointment appointment = appointmentService.get(id);
		if(lang != null && "2".equals(lang)) {
			clinicService.setEngLang(appointment.getClinic());
			doctorService.setEngLang(appointment.getDoctor());
		}
		return appointment;
	}
	
	@PostMapping(value = "cancalAppointment")
	@ResponseBody
	public String cancalAppointment(String id, String reason, String remarks) {		
		Appointment appointment = appointmentService.get(id);
		if(!Utils.checkTime(appointment.getScheduledTime(), appointment.getTimePeriod())){
			Clinic c = clinicService.get(appointment.getClinic());
			return "系统暂时无法取消您的预约，请致电客服" + c.getTelephone() + "完成预约取消或者改约。";
		}
		appointment.setReason(reason);
		appointment.setAppointmentStatus("5");
		appointment.setRemarks(remarks);
		appointmentService.save(appointment);
		return "1";
	}
	
	@PostMapping(value = "saveAppointment")
	@ResponseBody
	public String saveAppointment(String clinicId, String department,String scheduledTime, String timePeriod, String remarks) {
		Appointment appointment = new Appointment();
		Clinic clinic = clinicService.get(clinicId);
		appointment.setClinic(clinic);
		appointment.setArea(clinic.getCity());
		appointment.setDepartment(department);
		Date date = null;
		try{
			date = DateUtils.parseDate(scheduledTime, "yyyy-MM-dd");
		}catch(Exception e){
			e.printStackTrace();
			date = new Date();
		}
		appointment.setScheduledTime(date);
		appointment.setTimePeriod(timePeriod);
		appointment.setRemarks(remarks);
		appointment.setAppointmentStatus("1");
		User user = UserUtils.getUser();
        Leaguer leaguer = leaguerService.get(user.getRefCode());
        appointment.setLeaguer(leaguer);
		appointmentService.save(appointment);
		return "1";
	}
	
	@RequestMapping(value = "appointment")
	public String appointment(Model model) {
        User user = UserUtils.getUser();
        Leaguer leaguer = leaguerService.get(user.getRefCode());
        Appointment entity = new Appointment();
        entity.setStatus("0");
        entity.setLeaguer(leaguer);
        List<Appointment> list = appointmentService.findList(entity);
        model.addAttribute("list", list);
		return "modules/fl/appointment";
	}
	
	@PostMapping(value = "saveLeaguer")
	@ResponseBody
	public String saveLeaguer(String realName, String sex,String birthday, String certificateType, String idNumber, Boolean hasAllergicHistory, String allergicHistory) {
		User user = UserUtils.getUser();
        Leaguer leaguer = leaguerService.get(user.getRefCode());
        leaguer.setRealName(realName);
        leaguer.setSex(sex);
        Date date = null;
		try{
			date = DateUtils.parseDate(birthday, "yyyy-MM-dd");
		}catch(Exception e){
			e.printStackTrace();
			date = new Date();
		}
        leaguer.setBirthday(date);
        leaguer.setAllergicHistory(allergicHistory);
        leaguer.setHasAllergicHistory(hasAllergicHistory);
        leaguer.setCertificateType(certificateType);
        leaguer.setIdNumber(idNumber);
        leaguerService.save(leaguer);
        return "1";
	}
	
	@RequestMapping(value = "setLang")
	@ResponseBody
	public String setLang(String lang){
		User user = UserUtils.getUser();
        Leaguer leaguer = leaguerService.get(user.getRefCode());
        leaguer.setLanguage(lang);
        leaguerService.save(leaguer);
		return "1";
	}
}
